﻿using System;
using System.Drawing;
using System.Windows.Forms;
using DSkin.Forms;
using CefSharp;
using CefSharp.WinForms;
using System.Runtime.InteropServices;
using System.Text;
using System.IO;
using System.Threading;
using System.Net;
using System.Collections.Specialized;

namespace wfaResClient
{
    
    public partial class FrmMain : DSkinForm
    { 
        DeviceControl dc = new DeviceControl();
        JavascriptCsharp jc = new JavascriptCsharp();
        public FrmMain()
        {
            InitializeComponent();
            InitializeBrowserControl();
        }
        public void InitializeBrowserControl()
        {
            PublicData.Aid = "02838566012";
            jc.browser = new ChromiumWebBrowser(jc.GetPagePath("index.html"))//首先加载的是电话薄
            {
                Dock = DockStyle.Fill
            };
            controlHost1.Controls.Add(jc.browser);
            CefSharpSettings.LegacyJavascriptBindingEnabled = true;
            jc.browser.RegisterJsObject("JCall", jc);//注册js事件
            jc.browser.FrameLoadEnd += jc.OnFrameLoadEnd;
            jc.browser.IsBrowserInitializedChanged += jc.OnIsBrowserInitializedChanged;//添加事件 
        }
 
        # region 窗体代码块
        internal AnchorStyles StopAanhor = AnchorStyles.None;//以下为窗体吸附函数

        public ThreadStart ThreadMethod { get; private set; }

        private void mStopAnhor()
        {
            if (this.Top <= 0 && this.Left <= 0)
            {
                StopAanhor = AnchorStyles.None;
            }
            else if (this.Top <= 0)
            {
                StopAanhor = AnchorStyles.Top;
            }
            else if (this.Left <= 0)
            {
                StopAanhor = AnchorStyles.Left;
            }
            else if (this.Left >= Screen.PrimaryScreen.Bounds.Width - this.Width)
            {
                StopAanhor = AnchorStyles.Right;
            }
            else if (this.Top >= Screen.PrimaryScreen.Bounds.Height - this.Height)
            {
                StopAanhor = AnchorStyles.Bottom;
            }
            else
            {
                StopAanhor = AnchorStyles.None;
            }
        }
        public void wd_initial_position(int x, int y)
        {
            //设置窗体初始位置
            if (x == 0 || y == 0)
            {
                this.Top = 12;
                this.Left = Screen.PrimaryScreen.Bounds.Width - this.Width - 25;
            }
            else
            {
                this.Top = x;
                this.Left = y;
            }
        }

        /// <summary>
        /// 获取远程头像
        /// </summary>
        /// <param name="strUrl">url地址</param>
        public void get_head_image(string strUrl)
        {
            //获取远程用户头像
            string url = string.Format(@strUrl);
            System.Net.WebRequest webreq = System.Net.WebRequest.Create(url);
            System.Net.WebResponse webres = webreq.GetResponse();
            using (System.IO.Stream stream = webres.GetResponseStream())
            {
                this.pbHead.Image = Image.FromStream(stream); ;
            }
        }

        private void dsiSysMenu_MouseDown(object sender, MouseEventArgs e)
        {
            //打开系统菜单
            if (e.Button == MouseButtons.Left)
            {
                dcmsSysMenu.Show(dsiSysMenu, new Point(e.X, e.Y));
            }
        }

        private void dsiSysMenu_MouseHover(object sender, EventArgs e)
        {
            //设置主菜单按钮背景色
            dsiSysMenu.BackColor = Color.DodgerBlue;
        }

        private void dsiSysMenu_MouseLeave(object sender, EventArgs e)
        {
            //恢复主菜单按钮背景色透明
            dsiSysMenu.BackColor = Color.Transparent;
        }

        private void frmMain_Resize(object sender, EventArgs e)
        {
            //窗体最小化时从任务栏隐藏
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.ShowInTaskbar = false;
            }
        }

        private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            Properties.Settings.Default.SaveHeight = this.Height;//保存改变高度
            Properties.Settings.Default.Save();//保存当前记录
            Properties.Settings.Default.SaveWith = this.Width;
            Properties.Settings.Default.Save();
            //关闭按钮时最小化窗体
            if (e.CloseReason == CloseReason.UserClosing)
            {
                e.Cancel = true;
                this.WindowState = FormWindowState.Minimized;
                this.ShowInTaskbar = false;
            }
        }
        private void nifSystem_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                //鼠标单击时最小化与还原
                if (this.WindowState == FormWindowState.Normal)
                {
                    //最小化
                    this.WindowState = FormWindowState.Minimized;
                    this.ShowInTaskbar = false;
                }
                else if (WindowState == FormWindowState.Minimized)
                {
                    //还原窗体
                    this.WindowState = FormWindowState.Normal;
                    this.ShowInTaskbar = true;
                    this.TopMost = true;
                }
            }
        }

        private void tsmiQuit_Click(object sender, EventArgs e)
        {
            Properties.Settings.Default.SaveHeight = this.Height;//保存改变高度
            Properties.Settings.Default.Save();//保存当前记录
            Properties.Settings.Default.SaveWith = this.Width;
            Properties.Settings.Default.Save();
            //退出应用程序
            this.TopMost = false;
            if (MessageBox.Show("你确定要退出？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1) == DialogResult.Yes)
            {
                nifSystem.Visible = false;
                Cef.Shutdown();//关闭浏览器
                dc.ShutDownEquipment();//关闭设备
                Close();
                Dispose();
                System.Environment.Exit(System.Environment.ExitCode);
            }
        }
        private void frmMain_LocationChanged(object sender, EventArgs e)
        {
            //窗体位置发生改变时
            this.mStopAnhor();
        }

        private void sysTimer_Tick(object sender, EventArgs e)
        {
            //时钟函数检测窗体位置
            if (this.Bounds.Contains(Cursor.Position))
            {
                switch (this.StopAanhor)
                {
                    case AnchorStyles.Top:
                        this.Location = new Point(this.Location.X, 0);
                        break;
                    case AnchorStyles.Left:
                        this.Location = new Point(0, this.Location.Y);
                        break;
                    case AnchorStyles.Right:
                        this.Location = new Point(Screen.PrimaryScreen.Bounds.Width - this.Width, this.Location.Y);
                        break;
                    case AnchorStyles.Bottom:
                        this.Location = new Point(this.Location.X, Screen.PrimaryScreen.Bounds.Height - this.Height);
                        break;
                }
            }
            else
            {
                switch (this.StopAanhor)
                {
                    case AnchorStyles.Top:
                        this.Location = new Point(this.Location.X, (this.Height - 8) * (-1));
                        break;
                    case AnchorStyles.Left:
                        this.Location = new Point((-1) * (this.Width - 8), this.Location.Y);
                        break;
                    case AnchorStyles.Right:
                        this.Location = new Point(Screen.PrimaryScreen.Bounds.Width - 8, this.Location.Y);
                        break;
                    case AnchorStyles.Bottom:
                        this.Location = new Point(this.Location.X, (Screen.PrimaryScreen.Bounds.Height - 8));
                        break;
                }
            }
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            
            MinimumSize = new Size(Properties.Settings.Default.MinFrmWith, Properties.Settings.Default.MinFrmHeight);
            MaximumSize = new Size(Properties.Settings.Default.MaxFrmWith,Properties.Settings.Default.MaxFrmHeight);
            if (Properties.Settings.Default.SaveWith >= Properties.Settings.Default.MinFrmWith & Properties.Settings.Default.SaveWith<= Properties.Settings.Default.MaxFrmWith)
            {
                Width = Properties.Settings.Default.SaveWith;
                Height = Properties.Settings.Default.SaveHeight;
            }
            else
            {
                Width = Properties.Settings.Default.FrmWith;//加载默认大小
                Height = Properties.Settings.Default.FrmHeight;
            }
            dsiSysMenu.Location = new Point(this.Width - 100, 3);//固定菜单栏位置
            //窗体载入时初始化
            System.Windows.Forms.Timer StopRectTimer = new System.Windows.Forms.Timer();
            StopRectTimer.Tick += new EventHandler(sysTimer_Tick);
            StopRectTimer.Interval = 25;
            StopRectTimer.Enabled = true;
            this.TopMost = true;
            StopRectTimer.Start();
            //窗体初始化位置
            this.wd_initial_position(0, 0);
            //获取ID名
            if (PublicData.Name != "" && PublicData.Name != null)
            {
                dsLabel.Text = PublicData.Name;
            }
            //获取用户头像
            this.get_head_image(PublicData.hedImageUrl);
            //窗体绘制完成之后：
            if (Properties.Settings.Default.SelfStartingEquipment == 1)//判断是否自启设备
            {
                dc.openDevice((Int32)this.Handle);
            }
        }
        private void frmMain_SizeChanged(object sender, EventArgs e)
        {
            dsiSysMenu.Location = new Point(this.Width - 100, 3);// 固定菜单栏位置

        }//重启设备
        private void fdsaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            dc.RebootDevice((Int32)this.Handle);
        }
        private void fdsaToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            dc.openDevice((Int32)this.Handle);
        }
        private void fsaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            dc.ShutDownEquipment();
        }
        private void 系统设置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FrmSetting sys = new FrmSetting();
            sys.ShowDialog();
        }
        public static string FromASCIIByteArray(byte[] characters)//ASCCIIB编码
        {
            ASCIIEncoding encoding = new ASCIIEncoding();
            string constructedString = encoding.GetString(characters);
            return (constructedString);
        }
        public int alertNumber=0;
        protected override void DefWndProc(ref System.Windows.Forms.Message m)//windos消息机制推送，检测事件
        {
            switch (m.Msg)
            {
                case BriSDKLib.BRI_EVENT_MESSAGE:
                    {
                        BriSDKLib.TBriEvent_Data EventData = (BriSDKLib.TBriEvent_Data)Marshal.PtrToStructure(m.LParam, typeof(BriSDKLib.TBriEvent_Data));
                        string strValue = "";
                        switch (EventData.lEventType)
                        {
                            case BriSDKLib.BriEvent_PhoneHook:
                                {
                                    strValue = "通道" + (EventData.uChannelID + 1).ToString() + "：电话机摘机";//摘机
                                }
                                break;
                            case BriSDKLib.BriEvent_PhoneHang:
                                {
                                    strValue = "通道" + (EventData.uChannelID + 1).ToString() + "：电话机挂机";
                                    MessageBox.Show(strValue);
                                }
                                break;
                            case BriSDKLib.BriEvent_CallIn:
                                {
                                    dc.OffHorn();//关闭喇叭
                                    if (alertNumber == 0)//判断是否是同一个电话呼入
                                    {
                                        jc.browser.ExecuteScriptAsync(@"document.title='来电提醒';window.open('ContactsDial.html', '', 'width=400,height=400')"); //写入js
                                        alertNumber = 1;
                                    }
                                }
                                break;
                            case BriSDKLib.BriEvent_GetCallID:
                                {
                                    strValue = "通道" + (EventData.uChannelID + 1).ToString() + "：接收到来电号码 " + FromASCIIByteArray(EventData.szData);
                                    jc.browser.ExecuteScriptAsync(@"document.getElementById('inputNumber').value='" + strValue+"';");
                                }
                                break;
                            case BriSDKLib.BriEvent_StopCallIn:
                                {
                                    strValue = "通道" + (EventData.uChannelID + 1).ToString() + "：停止呼入，产生一个未接电话 ";
                                    alertNumber = 0;//重置判断同一呼入的变量
                                    jc.browser.ExecuteScriptAsync(@"alert('有未接来电：'" + strValue + "'')");
                                }
                                break;
                            case BriSDKLib.BriEvent_GetDTMFChar:
                                {
                                    //strValue = "通道" + (EventData.uChannelID + 1).ToString() + "：接收到按键 " + FromASCIIByteArray(EventData.szData);
                                }
                                break;
                            case BriSDKLib.BriEvent_RemoteHang:
                                {
                                    //strValue = "通道" + (EventData.uChannelID + 1).ToString() + "：远程挂机 ";
                                }
                                break;
                            case BriSDKLib.BriEvent_Busy:
                                {

                                    //strValue = "通道" + (EventData.uChannelID + 1).ToString() + "：接收到忙音,线路已经断开 ";
                                    //MessageBox.Show(strValue);
                                }
                                break;
                            case BriSDKLib.BriEvent_DialTone:
                                {
                                    //strValue = "通道" + (EventData.uChannelID + 1).ToString() + "：检测到拨号音 ";
                                    //MessageBox.Show(strValue);
                                }
                                break;
                            case BriSDKLib.BriEvent_PhoneDial:
                                {
                                    //strValue = "通道" + (EventData.uChannelID + 1).ToString() + "：电话机拨号 " + FromASCIIByteArray(EventData.szData);
                                }
                                break;
                            case BriSDKLib.BriEvent_RingBack:
                                {
                                    //strValue = "通道" + (EventData.uChannelID + 1).ToString() + "：拨号后接收到回铃音 ";
                                    //MessageBox.Show(strValue);
                                }
                                break;
                            case BriSDKLib.BriEvent_DevErr:
                                {
                                    if (EventData.lResult == 3)
                                    {
                                        strValue = "通道" + (EventData.uChannelID + 1).ToString() + "：设备可能被移除 ";
                                        MessageBox.Show(strValue);
                                    }
                                }
                                break;
                            default:
                                break;
                        }
                    }
                    break;
                default:
                    base.DefWndProc(ref m);
                    break;
            }
        }
        private void dSkinLabel1_DoubleClick(object sender, EventArgs e)//编辑个性签名
        {
        }
        private void frmMain_ResizeBegin(object sender, EventArgs e)//改变窗体大小时发生
        {
            
            //窗体改变大小前提示
            //加入判断当前是不是最大窗体和最小窗体
            //如果是就不能在改变了
        }
        private void dskinCall_Click(object sender, EventArgs e)
        {
            jc.browser.Load(jc.GetPagePath("index.html"));//Mainform界面转电话薄
        }
        private void dSkinNote_Click(object sender, EventArgs e)//跳转记事本页面
        {
            jc.browser.Load(PublicData.notebookUrl);
        }

        private void toolStripMenuItem8_Click(object sender, EventArgs e)//托盘-设置
        {
            系统设置ToolStripMenuItem_Click(sender, e);
        }

        private void toolStripMenuItem5_Click(object sender, EventArgs e)
        {
            FrmAbout fb = new FrmAbout();//打开关于窗体
            fb.ShowDialog();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            jc.browser.ShowDevTools();
        }
    }
    #endregion
}
